package com.shop.autoshop.pay.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author lyt
 * @version 1.0.0
 * @ClassName AlipayConfiguration.java
 * @Description TODO
 * @createTime 2022年07月27日 14:12:00
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(AlipayProperty.class)
public class AliPayConfiguration {


    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    @Resource
    private AlipayProperty alipayProperty;

    @Bean
    public AlipayClient alipayClient(){

        String alipayPublicKeyPath = alipayProperty.getAlipayPublicKeyPath();
        String alipayPublicKey = this.content(alipayPublicKeyPath);
        String appPrivateKeyPath = alipayProperty.getAppPrivateKeyPath();
        String appPrivateKey = this.content(appPrivateKeyPath);

        alipayProperty.setAlipayPublicKey(alipayPublicKey);
        alipayProperty.setAppPrivateKey(appPrivateKey);

        return new DefaultAlipayClient(
                alipayProperty.getGatewayUrl(),
                alipayProperty.getAppId(),
                appPrivateKey,
                alipayProperty.getFormate(),
                alipayProperty.getCharset(),
                alipayPublicKey,
                alipayProperty.getSignType());
    }

    public Date alipayNotifyDateFormat(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        try {
            return simpleDateFormat.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    public String content(String filePath) {
        try {
            File file = new File(filePath);
            List<String> list = FileUtils.readLines(file, "UTF-8");
            StringBuilder sb = new StringBuilder();
            for (String ss : list) {
                sb.append(ss);
            }
            return sb.toString();
        } catch (Exception e) {
            log.error("获得支付配置异常：{}", e.getMessage());
            return null;
        }
    }
}